package com.gjszn.kh.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.gjszn.kh.context.SysContext;
import com.gjszn.kh.dao.UserMapper;
import com.gjszn.kh.mail.MailSenderUtil;
import com.gjszn.kh.model.HtmlMailBean;
import com.gjszn.kh.model.User;
import com.gjszn.kh.model.UserVO;
import com.gjszn.kh.utils.CIDUtils;
import com.gjszn.kh.utils.DateUtil;
import com.gjszn.kh.utils.FreemarkerUtil;

/**
 * user服务层
 * @author 姬亚赛
 *
 */
@Service
public class UserService {
	private static Logger log = LogManager.getRootLogger();
	@Inject
	private UserMapper userMapper;
	@Inject
	private MailSenderUtil mailSenderUtil;
	/**
	 * 根据会员编号，排序列名进行分页查询
	 * 
	 * @param member
	 * @param sortName
	 * @param isDESC
	 * @param page
	 * @param rows
	 * @return List<User>
	 */
	public List<UserVO> list(String member, String sortName, boolean isDESC, int page, int rows){
		int _rows = rows >= 1 ? rows : 10;
		int start = page >= 1 ? (page-1)*_rows : 0;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("member", member);
		map.put("sort", sortName);
		map.put("dir", isDESC ? "DESC" : "ASC");
		map.put("start", start);
		map.put("count", _rows);
		return userMapper.selectForPageByMember(map);
	}
	
	public List<UserVO> queryData(
			String name, 
			String number, 
			String code, 
			String startDate, 
			String endDate, 
			Integer status, 
			String member, 
			String sortName, boolean isDESC, int page, int rows){
		int _rows = rows >= 1 ? rows : 10;
		int start = page >= 1 ? (page-1)*_rows : 0;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("member", member);
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		map.put("code", code);
		map.put("name", name);
		map.put("number", number);
		map.put("sort", sortName);
		map.put("status", status);
		map.put("dir", isDESC ? "DESC" : "ASC");
		map.put("start", start);
		map.put("rows", _rows);
		
		log.info("查询的map:" + map);
		
		return userMapper.selectForPageByMember(map);
	}
	
	public int queryDataTotal(String name, 
			String number, 
			String code, 
			String startDate, 
			String endDate, 
			Integer status, 
			String member){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("member", member);
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		map.put("name", name);
		map.put("number", number);
		map.put("status", status);
		map.put("code", code);
		
		//log.info("total:" + map.toString());
		
		return userMapper.selectForPageByMemberOfTotal(map);
	}
	
	/**
	 * 将user数据插入到数据库中
	 * @param user
	 * @return
	 */
	public boolean add(User user){
		if(userMapper.insertSelective(user) == 1){
			int id = userMapper.selectId();
			log.info(user + "插入成功,id:" + id);
			return true;
		}else{
			log.info(user + "插入失败");
		}
		return false;
	}
	
	/**
	 * 通过id查询一行数据
	 * @param id
	 * @return User
	 */
	public User getById(int id){
		return userMapper.selectByPrimaryKey(id);
	}
	
	/**
	 * 会员单位为注册客户开出了交易账号
	 * @param id
	 * @param number
	 * @return boolean
	 */
	public boolean updateCreateNumber(int id, String number){
		User user = getById(id);
		if(user == null){
			return false;
		}
		user.setNumber(number);
		user.setStatus(SysContext.STATUS_CREATE_NUMBER);
		user.setRemark(user.getRemark() + "|会员单位为客户开出了交易账号");
		user.setCdate(DateUtil.getNowDateTime()); // 添加账号创建时间
		userMapper.updateByPrimaryKeySelective(user);
		return true;
	}
	
	/**
	 * 交易中心对交易账号进行激活
	 * @param id
	 * @return boolean
	 */
	public boolean updateActiveNumber(int id){
		User user = getById(id);
		if(user == null){
			return false;
		}
		user.setStatus(SysContext.STATUS_NUMBER_ACTIVATED);
		user.setRemark(user.getRemark() + "|交易中心已经对交易账号进行了激活");
		user.setAdate(DateUtil.getNowDateTime()); // 添加账号创建时间
		userMapper.updateByPrimaryKeySelective(user);
		return true;
	}
	
	
	/**
	 * 交易中心对交易账号进行激活
	 * @param id
	 * @return boolean
	 */
	public boolean updateApproveNumber(int id, String baseUrl){
		try {
			User user = getById(id);
			if(user == null){
				return false;
			}
			user.setStatus(SysContext.STATUS_NUMBER_PRE_SIGN);
			user.setRemark(user.getRemark() + "|交易中心已经对交易账号进行了激活");
			user.setAdate(DateUtil.getNowDateTime()); // 添加账号创建时间
			userMapper.updateByPrimaryKeySelective(user);
			// 发送激活邮箱
			HtmlMailBean mailBeans = new HtmlMailBean();
			mailBeans.setSubject(mailSenderUtil.getSubjectMark() + user.getName());
			mailBeans.setTo(user.getEmail());
			Map<String, Object> rootData = new HashMap<String, Object>();
			rootData.put("name", user.getName());
			rootData.put("sex",CIDUtils.getGender(user.getCid()));
			rootData.put("baseUrl", baseUrl);
			rootData.put("userId", id + "");
			String mailContent = FreemarkerUtil.getFreemarkViewString("mail_activated.ftl", rootData);
			mailBeans.setContent(mailContent);
			mailSenderUtil.sendMail(mailBeans);
		} catch (Exception e) {
			log.warn(e.getMessage());
			return false;
		}
		return true;
	}
	
	
	/**
	 * 将user数据插入到数据库中,并返回id，
	 * @param user
	 * @return
	 */
	public int addBackId(User user){
		if(userMapper.insertSelective(user) == 1){
			int id = userMapper.selectId();
			log.info(user + "插入成功,id:" + id);
			return id;
		}else{
			log.info(user + "插入失败");
		}
		return -1;
	}
	
	/**
	 * 检查身份证号是否注册过，如果注册过则返回true，否则返回false
	 * @param CID
	 * @return
	 */
	public boolean isCIDExist(String CID){
		User user = userMapper.selectByCID(CID);
		if(user!=null){
			return true;
		}
		return false;
	}
	
	/**
	 * 检查手机号码是否注册过，如果注册过则返回true，否则返回false
	 * @param phone
	 * @return
	 */
	public boolean isPhoneExist(String phone){
		User user = userMapper.selectByPhone(phone);
		if(user!=null){
			return true;
		}
		return false;
	}
	
	public int total(String member){
		return userMapper.selectTotal(member);
	}
	
	public boolean delete(int id, String member){
		if(userMapper.deleteByPrimaryKey(id, member) == 1){
			log.info("客户id=" + id + "被" + ("admin".equals(member)? "admin" : member) + "删除了");
			return true;
		}
		return false;
	}
	
	// 修改客户注册的信息的删除状态
	public int updateForDeleted(int id) {
		return userMapper.updateForDeleted(id);
	}
}
